package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.PageResult;
import cn.itcast.hotel.dto.RequestParam;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;

    @Override
    public PageResult<HotelDoc> searchHotelList(RequestParam param) {
        //获取参数key，page，size
        String key = param.getKey();
        int page = param.getPage();
        int size = param.getSize();
        SearchRequest request = new SearchRequest("hotel");
        FunctionScoreQueryBuilder scoreQuery = queryBuilder(param);
        request.source().query(scoreQuery);
        //分页,高亮
        request.source().from((page-1)*size).size(size);
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        //按找距离排序
        if (param.getLocation() != null && !param.getLocation().equals("")){
            request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(param.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }
        //发送查询请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //解析返回数据,返回PageResult
        return key == null ? handleResponse(response):handleHighlightResponse(response);
    }

    @Override
    public Map<String, List<String>> getMultiAggregation(RequestParam param) {
        Map<String, List<String>> map = new HashMap<>();
        SearchRequest request = new SearchRequest("hotel");
        FunctionScoreQueryBuilder functionScoreQueryBuilder = queryBuilder(param);
        request.source().query(functionScoreQueryBuilder);
        request.source().size(0);
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(20));
        request.source().aggregation(AggregationBuilders.terms("starAgg").field("starName").size(20));
//        request.source().aggregation();
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println("response = " + response);
        Aggregations aggregations = response.getAggregations();
        List listCity = getAggList(aggregations,"cityAgg");
        map.put("city",listCity);
        List listStar = getAggList(aggregations,"starAgg");
        map.put("starName",listStar);
        List listBrand = getAggList(aggregations,"brandAgg");
        map.put("brand",listBrand);
        return map;
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        List<String> suggestList = new ArrayList<>();
        try {
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(new SuggestBuilder().addSuggestion("my_suggestion",
                    SuggestBuilders.completionSuggestion("suggestion").prefix(prefix).skipDuplicates(true).size(10)));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                String suggest = option.getText().toString();
                suggestList.add(suggest);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return suggestList;
    }

    private List getAggList(Aggregations aggregations,String aggName) {
        Terms brandAgg = aggregations.get(aggName);
        List list = new ArrayList<String>();
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for(Terms.Bucket bucket:buckets){
            String key = bucket.getKeyAsString();
            list.add(key);
//            System.out.println("key = " + key);
        }
        return list;
    }

    private FunctionScoreQueryBuilder queryBuilder(RequestParam param) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //根据搜索字段查询
        if (!StringUtils.isEmpty(param.getKey())){
            boolQuery.must(QueryBuilders.matchQuery("all", param.getKey()));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //city
        if (!StringUtils.isEmpty(param.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city", param.getCity()));
        }
        //brand
        if (!StringUtils.isEmpty(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand", param.getBrand()));
        }
        //starName
        if (!StringUtils.isEmpty(param.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName", param.getStarName()));
        }
        //range
        if (param.getMinPrice()!=null && param.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()).lte(param.getMaxPrice()));
        }
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery("isAD", true),
                        ScoreFunctionBuilders.weightFactorFunction(10)
                )
        });
        return functionScoreQuery;
    }

    private PageResult<HotelDoc> handleHighlightResponse(SearchResponse response) {

        SearchHits searchHits = response.getHits();
        TotalHits totalHits = searchHits.getTotalHits();
        SearchHit[] list = searchHits.getHits();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit one:list){
            String json = one.getSourceAsString();
            Map<String, HighlightField> fields = one.getHighlightFields();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            Object[] sortValues = one.getSortValues();
            if (sortValues.length > 0){
                hotelDoc.setDistance(sortValues[0]);
            }
            if (!CollectionUtils.isEmpty(fields)){
                HighlightField highlightField = fields.get("name");
                if (highlightField !=null){
                    String name = highlightField.getFragments()[0].toString();
                    hotelDoc.setName(name);
                }
            }
            hotelDocs.add(hotelDoc);
        }
        return new PageResult<>(totalHits.value, hotelDocs);
    }
    private PageResult<HotelDoc> handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        TotalHits totalHits = searchHits.getTotalHits();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
        SearchHit[] list = searchHits.getHits();
        for (SearchHit one:list){
            String json = one.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            Object[] sortValues = one.getSortValues();
            if (sortValues.length > 0){
                hotelDoc.setDistance(sortValues[0]);
            }
            hotelDocs.add(hotelDoc);
        }
        return new PageResult<>(totalHits.value,hotelDocs);
    }
}
